package cn.i96688.scanclient.service.impl;


import com.alibaba.fastjson.JSONObject;
import cn.i96688.scanclient.bean.MerInfo;
import cn.i96688.scanclient.bean.PayLog;
import cn.i96688.scanclient.bean.Status;
import cn.i96688.scanclient.service.MerchantService;
import cn.i96688.scanclient.utils.ConfParams;
import cn.i96688.scanclient.utils.Constants;
import cn.i96688.scanclient.utils.HttpRequest;
import cn.i96688.scanclient.utils.LocalStore;

public class MerchantServiceImpl implements MerchantService {
//	private Logger log=Logger.getLogger(ParameterServiceImpl.class);
	
	
	@Override
	public String login(JSONObject json) {
		String url=ConfParams.getValueByKey("server.url")+Constants.URI_MER_LOGIN;
		JSONObject respJson=null;
		try {
			String str=HttpRequest.sendPost(url, json.toString());
			respJson=JSONObject.parseObject(str);
			if(Status.isFail(respJson)){
				return respJson.getString(Status.NAME_MSG);
			}
		} catch (Exception e) {
			PayLog.getInstance().addLog("登录出错："+url);
			PayLog.getInstance().addLogs(e);
			return "登录失败";
		}
		JSONObject merInfo=new JSONObject();
		merInfo.put("merId", respJson.getString("merId"));
		merInfo.put("merName", respJson.getString("merName"));
		LocalStore.getInstance().writeMerInf(merInfo);
		return MerInfo.getInstance().load(respJson);
	}
	
	@Override
	public JSONObject getMerInf(){
		JSONObject tmpMer=LocalStore.getInstance().getMerInf();
		String url=ConfParams.getValueByKey("server.url")+Constants.URI_MER_GET;
		JSONObject respJson=null;
		try {
			JSONObject params=new JSONObject();
			params.put("merId", tmpMer.getString("merId"));
			params.put("deviceName", ConfParams.getValueByKey("deviceName"));
			String str=HttpRequest.sendPost(url, params.toJSONString());
			respJson=JSONObject.parseObject(str);
			if(Status.isFail(respJson)){
				return respJson;
			}
		} catch (Exception e) {
			PayLog.getInstance().addLog("获取商户出错："+url);
			PayLog.getInstance().addLogs(e);
			return Status.fail("获取商户出错");
		}
		MerInfo merInfo=MerInfo.getInstance();
		String msg=merInfo.load(respJson);
		if(msg.length()>0){
			return Status.fail(msg);
		}
		return merInfo.getMerInf();
	}

}
